<?php
/**
 * User: AK.
 * Date: 2019/7/17
 * 完成用户登录、注册、验证token等功能
 */
class Auth extends CI_Model{

    /**
     * save_token
     * @param int $userid
     * @param int $tokenid
     * @return true
     */
	 
    public function save_token($userid,$tokenid,$userinfo){

		//先删除，再插入
		
		if(isset($userid) && isset($tokenid)){
			$data['userid'] = $userid;
			$data['tokenid'] = $tokenid;
			$data['userinfo'] = $userinfo;
			$this->db->where("userid",$userid);
			$this->db->delete('app_session');
			$this->db->insert('app_session',$data);
			return true;
		}
		return false;
    }
	
    /**
     * user login
     * @param varchar $tokenid
     * @return true
     */
    public function token_exist($tokenid){
		if(isset($tokenid)){
			$this->db->select("userid");
			$this->db->where("tokenid",$tokenid);
			
			$this->db->from('app_session');
			return $this->db->get()->num_rows();
		}else{
			return false;
		}
    }	
	
	//根据tokenid清除app_session
    public function del_token($tokenid){
		if(isset($tokenid)){
			$this->db->where("tokenid",$tokenid);
			$this->db->delete('app_session');
			return true;
		}else{
			return false;
		}
    }	
	
	//获取app_session
	public function get_app_session($uid){
        $this->db->select("*");
        $this->db->where("userid",$uid);
        $this->db->from('app_session');
        $query = $this->db->get();

        return $query->row_array();   
	}
	
	
	//删除
    public function del_smssend($mobile){
		//先删除，再插入
		if(isset($mobile)){
			$this->db->where("mobile",$mobile);
			$this->db->delete('send_sms');
			return true;
		}
		return false;
    }	

	//删除
    public function del_appuser($mobile){
		//先删除，再插入
		if(isset($mobile)){
			$this->db->where("mobile",$mobile);
			$this->db->delete('app_user');
			return true;
		}
		return false;
    }
	
	//删除
    public function del_appsession($userid){
		//先删除，再插入
		if(isset($userid)){
			$this->db->where("userid",$userid);
			$this->db->delete('app_session');
			return true;
		}
		return false;
    }


    /**
     * user register
     * @param userinfo['mobile'],userinfo['truename'],userinfo['password']
     * @return true
     */
    public function register_in($userinfo){
		$res_info = array();
		$res_info['code'] = '1001';
		$res_info['msg'] = '注册失败';
		$res_info['data'] = '';
		if(isset($userinfo['truename'])&&isset($userinfo['mobile'])&&isset($userinfo['password'])){
			$res_info['code'] = '0000';
			$res_info['msg'] = '注册成功';
			$data['mobile'] = $userinfo['mobile'];
			$data['truename'] = $userinfo['truename'];
			$data['originalpassword'] = $userinfo['password'];
			$data['password'] = md5(md5($userinfo['password']));
			$data['is_ts'] = 1;
			$data['is_dc'] = 1;
			$data['is_gt'] = 1;
			$mymenu['tcl'] = 1;
			$mymenu['dc'] = 1;
			$mymenu['dlg'] = 1;
			$data['mymenu'] = json_encode($mymenu);
			$data['csphone'] = '021-50184981';
			
			//注册开通试用，一天
			$nowdate = date('Y-n-d');
			$data['userlevel'] = 1;
			$data['p_begindate'] = $nowdate;
			$data['p_enddate'] = $nowdate;
			$data['r_date'] = date('Y-n-d H:i:s');
			$data['r_ip'] = $this->get_ip();
			$data['r_ly'] = 'APP';
			$data['email'] = '';
			$this->db->insert('app_user',$data);
			$data['userid'] =$this->db->insert_id();
			unset($data['originalpassword']);
			unset($data['password']);
			unset($data['r_ip']);
			unset($data['r_date']);
			unset($data['r_ly']);
			
			$res_info['data'] = $data;

		}
		return $res_info;
    }
	
	private function get_ip() 
	{
		//strcasecmp 比较两个字符，不区分大小写。返回0，>0，<0。
		if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
			$ip = getenv('HTTP_CLIENT_IP');
		} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
			$ip = getenv('REMOTE_ADDR');
		} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		$res =  preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
		return $res;
	}

	
    /**
     * 判断手机号是否存在
     * @param varchar $mobile
     * @return true
     */
    public function check_mobile($mobile){
        $this->db->select("mobile");
		if(isset($mobile)){
			$mobile = trim($mobile);
			$this->db->where("mobile",$mobile);
			$this->db->where("is_state",0);
			$this->db->from('store_app_user');
			return $this->db->get()->num_rows();
		}else{
			return false;
		}
    }
	
    /**
     * 判断用户名、密码是否正确
     * @param mobile password
     * @return $userinfo array()
     */
    public function check_mobile_pass($mobile,$password){
		$sql = "SELECT userid,mobile,truename,sex,email,is_ts,is_dc,is_gt,mymenu,csphone,tcl_myprice,dc_myprice,dlg_myprice,userlevel,p_begindate,p_enddate,is_state From store_app_user WHERE `is_state` = '0' ";
		$userinfo = array();
		$userinfo['code'] = '0004';
		$userinfo['msg'] = '手机号/密码错误';
		$userinfo['data'] = '';
		if(isset($mobile) && isset($password)){
			$mobile = trim($mobile);
			//密码加密
			$password = trim($password);
			$password = md5(md5($password));
			$sql .= "AND `mobile` = '$mobile' AND  `password` = '$password' ";
			$resarray = array();
			$resarray =$this->db->query($sql)->row_array();
			$nowdate = date("Y-n-d");
			$userinfo['data'] = $resarray;
			if(count($resarray)>0){
				//判断用户是否被禁用
				if($resarray['is_state'] == 1){
					$userinfo['code'] = '0007';
					$userinfo['msg'] = '用户已禁用';
					return $userinfo;
					exit;
				}
			
			
				//查找用户是否过期
				if(strtotime($resarray['p_enddate'])<strtotime($nowdate)){
					$userinfo['code'] = '0007';
					$userinfo['msg'] = '该用户已过期';
				}else{
					$userinfo['code'] = '0000';
					$userinfo['msg'] = '登录成功';
				}
			}
		}
		return $userinfo;
		
    }	
	
    /**
     * save sms send
     * @param $data['mobile'],$data['msg'],$data['sendtime']
     * @return true
     */
	 
    public function save_sms_send($data){
		//先删除，再插入
		if(isset($data)){
			$this->db->insert('send_sms',$data);
			return true;
		}
		return false;
    }	
	
	
	//更新用户自选价格信息
	public function set_app_myprice($data){
	
		//找出历史自选
		$myprcelb = $data['channel'];
		$oldmyprice = $data['userinfo'][$myprcelb];
		$nowmyprice = "";
		//根据op来判断是删除还是新增
		$op = $data['op'];
	    if($op == 'add'){
			$nowmyprice = $oldmyprice.",".$data['setid'];
		
		}elseif($op == 'del'){
			$nowmyprice = str_replace($data['setid'],"",$oldmyprice);
		}else{
			return false;
		}
		//$nowmyprice = str_replace(",,,","",$nowmyprice);
		
		$data['userinfo'][$myprcelb] = $nowmyprice;
		
		//更新自选价格字段
		//更新app_session
		$userid = $data['userinfo']['userid'];
		$tokenid = $data['userinfo']['tokenid'];
		//userinfo存入app_session时，拿掉tokenid
		unset($data['userinfo']['tokenid']);
		$userinfo = base64_encode(json_encode($data['userinfo']));
		$mydata = array();
		if($this->save_token($userid,$tokenid,$userinfo)){
			//更新app_user
			$this->db->where("userid",$userid);
			$mydata[$myprcelb] = $nowmyprice;
		    $this->db->update('app_user',$mydata);
		}else{
		
			 return false;
		}
		return true;
	}
	
	//更新用户自选价格信息
	public function update_user_passwd($userid,$data){
		$this->db->where("userid",$userid);
		$this->db->update('app_user',$data);
		$this->db->where("userid",$userid);
		$this->db->delete('app_session');		
	}
	
	
    /**
     * get sms send
     * @param $mobile
     * @return true
     */
    public function get_smsinfo($mobile)
	{
        $this->db->select("sendtime,astokenid,msg");
        $this->db->where("mobile",$mobile);
        $this->db->from('send_sms');
        $query = $this->db->get();
        if($query->num_rows() < 1)
            return false;
        return $query->row_array();    
	}

   
    //根据手机号，获取用户信息
	public function get_userinfo($mobile)
	{
        $this->db->select("*");
        $this->db->where("mobile",$mobile);
        $this->db->from('app_user');
        $query = $this->db->get();
        if($query->num_rows() < 1)
            return false;
        return $query->row_array();    
	}
    //根据用户ID，获取用户密码信息等
	public function get_userinfo_byid($userid)
	{
        $this->db->select("userid,password");
        $this->db->where("userid",$userid);
        $this->db->from('app_user');
        $query = $this->db->get();
        if($query->num_rows() < 1)
            return false;
        return $query->row_array();    
	}

}